/* Copyright 2024 Coremail
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import type common from '@ohos.app.ability.common';
import type { CAModel } from '@ohos/base/src/main/ets/basedata/CAData';
import { CABase } from '@ohos/base/src/main/ets/basedata/CAData';
import { FileUtil } from '@ohos/base/src/main/ets/utils/FileUtil';

export class CAUtil {
  public static async getCA(context: common.Context, email: string): Promise<string[]> {
    const caName: string[] = this.getCaName(email)
    if (caName.length < 2) {
      return []
    }
    return Promise.all(caName.map((value: string) => {
      return FileUtil.getContentFromRawFile(context, value)
    }))
  }

  public static getCaName(email: string): string[] {
    let caName: string[] = []
    if (email == null || email.length < 1) return caName
    let domain = email.substring(email.indexOf("@") + 1)
    if (domain == null || domain.length < 1) return caName
    let word: string[] = domain.split('.')
    const data = CABase.filter((value) => value.domain.indexOf(word[0]) > -1)
    if (data.length == 1) {
      caName = data[0].caStr
    } else if (data.length > 1) {
      let wordData: CAModel[] = []
      if (word.length > 1) {
        wordData = CABase.filter((value) => value.domain == word[0] + "." + word[1])
      } else {
        wordData = CABase.filter((value) => value.domain == domain)
      }
      if (wordData.length > 0) {
        caName = wordData[0].caStr
      } else {
        caName = data[0].caStr
      }
    }
    return caName
  }
}